const app = getApp()
const db = wx.cloud.database()
const _ = db.command

function formatDate(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    return [year, month, day].map(formatNumber).join('-') + ' ' +
        [hour, minute, second].map(formatNumber).join(':');
}

function formatNumber(n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
}

Page({
    data: {
        userId: '',  // 当前用户的 userId
        roomId: '',  // 聊天室 ID
        userInfo: {}, // 当前用户信息
        matchUserInfos: [], // 其他用户信息
        chats: [],  // 聊天消息记录
        textInputValue: '',  // 输入框的内容
        isSending: false // 发送状态，用于禁用发送按钮
    },

    onLoad(options) {
        console.log("页面开始加载，接收到的 options:", options);
        this.setData({
            userId: app.globalData.userId,
            roomId: app.globalData.deepseekId
        }, () => {
            console.log("userId 和 roomId 已设置，userId:", this.data.userId, "roomId:", this.data.roomId);
            this.initUserInfo();
            this.initChatMessages();
        });
    },

    initUserInfo() {
        console.log("开始初始化用户信息，当前记录的 userId:", this.data.userId);
        const that = this;
        // 查询当前用户信息
        db.collection('users').where({
            _id: this.data.userId
        }).get().then(res => {
            console.log("查询当前用户信息结果:", res.data);
            if (res.data.length > 0) {
                that.setData({
                    userInfo: res.data[0]
                }, () => {
                    console.log('当前用户信息已更新:', that.data.userInfo);
                });
            }
        }).catch(err => {
            console.error("查询当前用户信息出错:", err);
        });

        // 查询该聊天室中除当前用户外的所有其他用户信息
        db.collection('chatroomMembers').where({
            roomId: this.data.roomId,
            userId: _.neq(this.data.userId)
        }).get().then(memberRes => {
            console.log('chatroomMembers 查询结果:', memberRes.data);
            if (memberRes.data.length > 0) {
                const otherUserIds = memberRes.data.map(member => member.userId);
                db.collection('users').where({
                    _id: _.in(otherUserIds)
                }).get().then(userRes => {
                    console.log('查询其他用户信息结果:', userRes.data);
                    if (userRes.data.length > 0) {
                        that.setData({
                            matchUserInfos: userRes.data
                        }, () => {
                            console.log('其他用户信息已更新:', that.data.matchUserInfos);
                        });
                    }
                }).catch(err => {
                    console.error("查询其他用户信息出错:", err);
                });
            }
        }).catch(err => {
            console.error("查询 chatroomMembers 出错:", err);
        });
    },

    initChatMessages() {
        const that = this;
        // 先获取历史消息
        db.collection('messages').where({
            roomId: app.globalData.deepseekId
        }).orderBy('sendTimeTs', 'asc').get().then(res => {
            const formattedRecords = res.data.map(item => {
                item.formattedSendTime = formatDate(new Date(item.sendTimeTs));
                return item;
            });
            this.setData({ chats: formattedRecords }, () => {
                console.log('历史聊天记录已初始化，当前聊天记录数量:', this.data.chats.length);
                console.log('查看当前的chat', this.data.chats);
                this.goBottom();
            });
            // 再设置监听
            this.messageWatcher = db.collection('messages').where({
                roomId: app.globalData.deepseekId
            }).orderBy('sendTimeTs', 'asc').watch({
                onChange: this.onChange.bind(this),
                onError(err) {
                    console.error('监听聊天消息变化出错:', err);
                }
            });
        }).catch(err => {
            console.error('获取历史聊天记录出错:', err);
        });
    },

    onChange(e) {
        console.log("接收到聊天消息变化，变化的消息数量:", e.docs.length);
        e.docs.forEach(doc => {
            console.log('接收到的消息 roomId:', doc.roomId);
        });
        const newMessages = e.docs.map(doc => {
            // ​**处理DeepSeek身份**
            if (doc.senderId === "deepseek_official") {
                return {
                    ...doc,
                    formattedSendTime: formatDate(new Date(doc.sendTimeTs)),
                    isAI: true
                };
            }
            return {
                ...doc,
                formattedSendTime: formatDate(new Date(doc.sendTimeTs)),
                isAI: false
            };
        });
        // 过滤掉已存在的消息
        const uniqueMessages = newMessages.filter(newMsg => 
            !this.data.chats.some(existingMsg => existingMsg._id === newMsg._id)
        );
        this.setData({
            chats: [...this.data.chats, ...uniqueMessages]
        }, () => {
            console.log("聊天记录已更新，当前聊天记录数量:", this.data.chats.length);
            console.log("查看更新的聊天记录：", this.data.chats);
            this.goBottom();
        });
    },

    initchats(records) {
        console.log("开始初始化聊天记录，传入的记录数量:", records.length);
        console.log("查看传过来的消息:", records);
        const recordsWithFormattedTime = records.map(item => {
            item.formattedSendTime = formatDate(new Date(item.sendTimeTs));
            return item;
        });
        console.log('初始化的聊天记录:', recordsWithFormattedTime);
        this.setData({
            chats: recordsWithFormattedTime
        }, () => {
            console.log('这是第一个chats', this.data.chats);
            this.goBottom();
        });
    },

    getContent: function (e) {
        console.log('事件对象 e:', e);

        // 检查 e.detail 的类型，直接获取输入值
        const inputValue = typeof e.detail === 'string' ? e.detail : e.detail.value;

        if (inputValue !== undefined) {
            console.log('输入的值：', inputValue);
            this.setData({
                textInputValue: inputValue
            }, () => {
                console.log('更新后的 textInputValue：', this.data.textInputValue);
            });
        } else {
            console.error('获取输入值失败，事件对象或输入值无效');
        }
    },

    sendMsg() {
        console.log("开始执行发送消息操作");
        let that = this;
        var show = false;
        if (this.data.chats.length === 0 || (Date.now() - this.data.chats[this.data.chats.length - 1].sendTimeTs > 120000)) {
            show = true;
        }

        if (!that.data.textInputValue.trim()) {
            console.log("尝试发送空白信息，已阻止");
            wx.showToast({
                title: '不能发送空白信息',
                icon: 'none',
            });
            return;
        }

        // 禁用发送按钮
        that.setData({
            isSending: true
        });

        const message = {
            roomId: that.data.roomId,
            senderId: that.data.userId,
            content: that.data.textInputValue,
            sendTimeTs: Date.now(),
            likeCount: 0,
            collectCount: 0,
            showTime: show
        };
        const userMessageContent = this.data.textInputValue; // 保存用户输入内容

        // 检查用户是否已经在 chatroomMembers 表中
        db.collection('chatroomMembers').where({
            roomId: that.data.roomId,
            userId: that.data.userId
        }).get().then(res => {
            console.log('检查用户是否在 chatroomMembers 表中的结果:', res.data);
            if (res.data.length === 0) {
                // 用户不在 chatroomMembers 表中，插入用户信息
                const memberInfo = {
                    roomId: that.data.roomId,
                    userId: that.data.userId,
                    joinedAt: new Date(),
                    role: 'member'
                };
                return db.collection('chatroomMembers').add({
                    data: memberInfo
                }).then(() => {
                    console.log('用户信息已插入 chatroomMembers 表');
                });
            }
            return Promise.resolve();
        }).then(() => {
            // 插入消息
            return db.collection('messages').add({
                data: message
            }).then(res => {
                console.log('消息已插入 messages 表，返回的 _id:', res._id);
                that.setData({
                    textInputValue: ""
                });
                // 插入用户消息后，立即触发 DeepSeek 回复
                return wx.cloud.callFunction({
                    name: 'BlueLM-70BAPI',
                    data: {
                        // 注意这里参数名要和云函数一致
                        prompt: userMessageContent 
                    }
                }).then(res => {
                    console.log("res的内容是："+res.result.data);
                    if (typeof res.result.data === 'string') {
                        // 若成功获取到回复内容
                        const replyMessage = {
                            roomId: that.data.roomId,
                            senderId: "deepseek_official",
                            content: res.result.data,
                            sendTimeTs: Date.now(),
                            likeCount: 0,
                            collectCount: 0,
                            showTime: false
                        };

                        // 将 DeepSeek 的回复插入到 messages 集合中
                        return db.collection('messages').add({
                            data: replyMessage
                        }).then(insertRes => {
                            console.log('DeepSeek 回复已插入 messages 表，返回的 _id:', insertRes._id);
                        });
                    } else {
                        console.error('DeepSeek 回复失败:', res.result.errMsg);
                        wx.showToast({
                            title: 'AI回复失败',
                            icon: 'none'
                        });
                    }
                }).catch(err => {
                    console.error('AI回复失败:', err);
                    wx.showToast({
                        title: 'AI回复失败',
                        icon: 'none'
                    });
                });
            });
        }).catch(err => {
            console.error('发送消息出错:', err);
            wx.showToast({
                title: '发送失败',
                icon: 'none'
            });
        }).finally(() => {
            // 启用发送按钮
            that.setData({
                isSending: false
            });
        });
    },

    goBottom() {
        console.log("开始执行滚动页面到底部操作");
        wx.createSelectorQuery().select('#page').boundingClientRect(function (rect) {
            if (rect) {
                // console.log("获取到 #page 的高度:", rect.height);
                wx.pageScrollTo({
                    scrollTop: rect.height + 4
                });
            } else {
                // console.error("未获取到 #page 的尺寸信息");
            }
        }).exec();
    },

    likeMessage(event) {
        const messageId = event.currentTarget.dataset.messageId;
        console.log("开始执行点赞操作，消息 ID:", messageId);
        if (!messageId) {
            console.error('messageId 为空，点赞操作终止');
            return;
        }
        const db = wx.cloud.database();
        const currentUser = this.data.userId;

        // 检查用户是否已经点赞
        db.collection('userActions').where({
            userId: currentUser,
            messageId: messageId,
            type: 'like'
        }).get().then(res => {
            console.log('检查用户是否已经点赞的结果:', res.data);
            if (res.data.length > 0) {
                // 取消点赞
                db.collection('userActions').doc(res.data[0]._id).remove().then(() => {
                    console.log('用户点赞记录已删除');
                    db.collection('messages').doc(messageId).update({
                        data: {
                            likeCount: _.inc(-1)
                        }
                    }).then(() => {
                        console.log('消息点赞数已更新');
                        wx.showToast({
                            title: '取消点赞成功',
                            icon: 'success'
                        });
                        // 更新本地数据
                        const updatedChats = this.data.chats.map(chat => {
                            if (chat._id === messageId) {
                                chat.likeCount--;
                            }
                            return chat;
                        });
                        this.setData({
                            chats: updatedChats
                        }, () => {
                            console.log('点赞操作后，当前聊天记录数量:', this.data.chats.length);
                        });
                    });
                });
            } else {
                // 点赞
                db.collection('userActions').add({
                    data: {
                        userId: currentUser,
                        messageId: messageId,
                        type: 'like',
                        createdAt: new Date()
                    }
                }).then(() => {
                    console.log('用户点赞记录已添加');
                    db.collection('messages').doc(messageId).update({
                        data: {
                            likeCount: _.inc(1)
                        }
                    }).then(() => {
                        console.log('消息点赞数已更新');
                        wx.showToast({
                            title: '点赞成功',
                            icon: 'success'
                        });
                        // 更新本地数据
                        const updatedChats = this.data.chats.map(chat => {
                            if (chat._id === messageId) {
                                chat.likeCount++;
                            }
                            return chat;
                        });
                        this.setData({
                            chats: updatedChats
                        }, () => {
                            console.log('点赞操作后，当前聊天记录数量:', this.data.chats.length);
                        });
                    });
                });
            }
        }).catch(err => {
            console.error('点赞操作出错:', err);
        });
    },

    collectMessage(event) {
        const messageId = event.currentTarget.dataset.messageId;
        console.log("开始执行收藏操作，消息 ID:", messageId);
        if (!messageId) {
            console.error('messageId 为空，收藏操作终止');
            return;
        }
        const db = wx.cloud.database();
        const currentUser = this.data.userId;

        // 检查用户是否已经收藏
        db.collection('userActions').where({
            userId: currentUser,
            messageId: messageId,
            type: 'collect'
        }).get().then(res => {
            console.log('检查用户是否已经收藏的结果:', res.data);
            if (res.data.length > 0) {
                // 取消收藏
                db.collection('userActions').doc(res.data[0]._id).remove().then(() => {
                    console.log('用户收藏记录已删除');
                    db.collection('messages').doc(messageId).update({
                        data: {
                            collectCount: _.inc(-1)
                        }
                    }).then(() => {
                        console.log('消息收藏数已更新');
                        wx.showToast({
                            title: '取消收藏成功',
                            icon: 'success'
                        });
                        // 更新本地数据
                        const updatedChats = this.data.chats.map(chat => {
                            if (chat._id === messageId) {
                                chat.collectCount--;
                            }
                            return chat;
                        });
                        this.setData({
                            chats: updatedChats
                        }, () => {
                            console.log('收藏操作后，当前聊天记录数量:', this.data.chats.length);
                        });
                    });
                });
            } else {
                // 收藏
                db.collection('userActions').add({
                    data: {
                        userId: currentUser,
                        messageId: messageId,
                        type: 'collect',
                        createdAt: new Date()
                    }
                }).then(() => {
                    console.log('用户收藏记录已添加');
                    db.collection('messages').doc(messageId).update({
                        data: {
                            collectCount: _.inc(1)
                        }
                    }).then(() => {
                        console.log('消息收藏数已更新');
                        wx.showToast({
                            title: '收藏成功',
                            icon: 'success'
                        });
                        // 更新本地数据
                        const updatedChats = this.data.chats.map(chat => {
                            if (chat._id === messageId) {
                                chat.collectCount++;
                            }
                            return chat;
                        });
                        this.setData({
                            chats: updatedChats
                        }, () => {
                            console.log('收藏操作后，当前聊天记录数量:', this.data.chats.length);
                        });
                    });
                });
            }
        }).catch(err => {
            console.error('收藏操作出错:', err);
        });
    },

    deleteMessage(event) {
        const messageId = event.currentTarget.dataset.messageId;
        console.log("开始执行删除消息操作，消息 ID:", messageId);
        if (!messageId) {
            console.error('messageId 为空，删除操作终止');
            return;
        }
        const db = wx.cloud.database();
        db.collection('messages').doc(messageId).remove().then(() => {
            console.log('消息已从数据库删除');
            wx.showToast({
                title: '删除成功',
                icon: 'success'
            });
            // 更新本地数据
            const updatedChats = this.data.chats.filter(chat => chat._id !== messageId);
            this.setData({
                chats: updatedChats
            }, () => {
                console.log('删除操作后，当前聊天记录数量:', this.data.chats.length);
            });
        }).catch(err => {
            console.error('删除消息出错:', err);
        });
    }
});